﻿using System;
using CoreVirtuoso.Helpers;
using OpenLink.Data.Virtuoso;
using VirtuosoDal.Repositories.RdfRepositories.Interfaces.VirtuosoCore;

namespace VirtuosoDal.Repositories.RdfRepositories.VirtuosoCore
{
   public class FullTextSearchRepository : IFullTextSearchRepository
   {
      public void AddToFullTextSearch(string graphUri, string predicateUri)
      {
         string connectionString = ConnectionStringsHelper.GetVirtuosoConnectionString();
         using (var connection = new VirtuosoConnection(connectionString))
         {
            var cmd = new VirtuosoCommand();

            if (predicateUri != null)
               predicateUri = String.Format("'{0}'", predicateUri);
            else
               predicateUri = "null";

            cmd.CommandText = String.Format("DB.DBA.RDF_OBJ_FT_RULE_ADD('{0}', {1}, '')", graphUri, predicateUri);
            cmd.Connection = connection;

            connection.Open();
            object result = cmd.ExecuteScalar();
            connection.Close();
         }
      }

      public void RemoveFromFullTextSearch(string graphUri, string propertyUri)
      {
         string connectionString = ConnectionStringsHelper.GetVirtuosoConnectionString();
         using (var connection = new VirtuosoConnection(connectionString))
         {
            var cmd = new VirtuosoCommand();
            cmd.CommandText = "DB.DBA.RDF_OBJ_FT_RULE_DEL(@rule_g, null, '')";
            cmd.Parameters.Add("@rule_g", graphUri);
            cmd.Parameters.Add("@rule_p", propertyUri);
            //cmd.Parameters.Add(new VirtuosoParameter("@reason", VirtDbType.VarChar).Value = "there surely should be a reason");

            cmd.Connection = connection;

            connection.Open();
            cmd.ExecuteNonQuery();
            connection.Close();
         }
      }

      public void SetFreeTextIndexAutoUpdate()
      {
         string connectionString = ConnectionStringsHelper.GetVirtuosoConnectionString();
         using (var connection = new VirtuosoConnection(connectionString))
         {
            var cmd = new VirtuosoCommand();
            cmd.CommandText = "DB.DBA.VT_BATCH_UPDATE('DB.DBA.RDF_OBJ', 'OFF', null)";

            cmd.Connection = connection;

            connection.Open();
            cmd.ExecuteNonQuery();
            connection.Close();
         }
      }
   }
}